$(function () {
    var ticketId = getQueryString('ticketId');
    var queryUrl = '../toolscheckticketitem/list';
    if (ticketId) {
        vm.ticketId = ticketId;
        queryUrl += '?ticketId=' + ticketId;
    }
    // 获取工单状态
    var state = getQueryString('state');
    var gridColModel = [
        {
            label: '编号', name: 'checkIndex', index: 'CHECK_INDEX', width: 50,
            formatter: function (value) {
                return value + '#';
            }
        },
        {label: '工装名称', name: 'toolsName', index: 'TOOLS_NAME', width: 140},
        {label: '工装编号', name: 'mapNo', index: 'MAP_NO', width: 200},
        {
            label: '检测周期', name: 'checkPeriod', index: 'CHECK_PERIOD', width: 70,
            formatter: function (value, col, row) {
                let checkPeriodDesc = '未知';
                if (row.checkPeriod == 1) {
                    checkPeriodDesc = '1次/月';
                } else if (row.checkPeriod == 3) {
                    checkPeriodDesc = '1次/季度';
                } else if (row.checkPeriod == 6) {
                    checkPeriodDesc = '1次/半年';
                } else if (row.checkPeriod == 12) {
                    checkPeriodDesc = '1次/年';
                }
                return checkPeriodDesc;
            }
        },
        {label: '判定标准', name: 'judgeStandard', index: 'JUDGE_STANDARD', width: 240},
        {label: '下限值', name: 'startInterval', index: 'START_INTERVAL', width: 80},
        {label: '上限值', name: 'endInterval', index: 'END_INTERVAL', width: 80},
        {label: '点位', name: 'position', index: 'POSITION', width: 60},
        {label: '测量值', name: 'measuredValue', index: 'MEASURED_VALUE', width: 60},
        {label: '工具编号', name: 'checkToolCode', index: 'CHECK_TOOL_CODE', width: 100},
        {
            label: '验证结果', name: 'validationResult', index: 'VALIDATION_RESULT', width: 70,
            formatter: function (value) {
                if ('OK' == value) {
                    return '合格';
                } else if ('NG' == value) {
                    return '不合格';
                } else {
                    return '';
                }
            }
        },
        {
            label: '检测时间', name: 'checkDate', index: 'CHECK_DATE', width: 80,
            formatter: function (value) {
                return transDate(value, "yyyy-MM-dd");
            }
        },
        {label: '检测人', name: 'checkerName', index: 'CHECKER', width: 80},
        {label: '处置意见', name: 'remark', index: 'remark', width: 160},
        {
            label: '处置时间', name: 'changeDate', index: 'CHANGE_DATE', width: 80,
            formatter: function (value) {
                return transDate(value, "yyyy-MM-dd");
            }
        },
        {label: '处置人', name: 'confirmorName', index: 'CONFIRMOR', width: 90},
        {label: '判定标准ID', name: 'judgeStandardId', index: 'JUDGE_STANDARD_ID', hidden: true},
        {label: '工装档案ID', name: 'toolsFileId', index: 'TOOLS_FILE_ID', hidden: true},
        {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
    ];
    if (state) {
        vm.state = state;
        if(vm.state == '1'){
            gridColModel[8].editable = true;
            gridColModel[8].editrules = {number: true};
            gridColModel[9].editable = true;
        }
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        shrinkToFit:false,
        autoScroll: true, //开启水平滚动条
        colModel: gridColModel,
        forceFit: true,
        cellEdit: true,
        cellsubmit: 'remote',
        cellurl: '../toolscheckticketitem/updateMeasuredValue',
        afterSaveCell: function (rowid, name, val, iRow, iCol) {
            vm.reload();
        },
        gridComplete: function () {
            var ids = $("#jqGrid").getDataIDs();
            for (var i = 0; i < ids.length; i++) {
                var rowData = $("#jqGrid").getRowData(ids[i]);
                if (rowData.validationResult == "不合格" && !rowData.changeDate) {//如果天数等于0，则背景色置灰显示
                    $('#' + ids[i]).find("td").addClass("SelectBG");
                }
            }
        }
    });
    vm.loadTicketToolsBaseList();
});

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        ticketId: '',// 工单ID
        state: 1, // 工单状态
        toolsCheckTicketItem: {
            remark: '',
            gmtModified: '',
            gmtCreate: '',
            confirmor: '',
            changeDate: '',
            checker: '',
            checkDate: '',
            validationResult: '',
            measuredValue: '',
            judgeStandardId: '',
            toolsFileId: '',
            id: '',
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        toolsBaseList: [], // 当前工单关联的工装列表
        q: {
            toolsFileId: '' // 工装档案ID
        },
        // 不合格记录的处置参数
        handleParam:{
            id: '',
            remark:''
        }
    },
    methods: {
        handle: function () {
            let _this = this;
            // 处置不合格项
            var selectedRowData = getSelectedRowData('#jqGrid');
            if(!selectedRowData){
                return;
            }
            if (!selectedRowData.measuredValue || !selectedRowData.validationResult) {
                alert("请等待测量结束后再进行处置！");
                return;
            }
            if (selectedRowData.validationResult == 'OK') {
                alert("当前点位无异常，无需处置！");
                return;
            }
            if (selectedRowData.remark) {
                alert("已处置，请勿重复操作！");
                return;
            }
            // 构建审批参数
            _this.handleParam = {
                id: selectedRowData.id,
                remark: ''
            }
            openWindow({
                title: '添加处置信息',
                area: ['550px', '300px'],
                content: jQuery("#reviewLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: '../toolscheckticketitem/handle',
                        params: JSON.stringify(_this.handleParam),
                        contentType: "application/json",
                        type: 'POST',
                        successCallback: function (res) {
                            alert('添加成功!', function (index) {
                                location.reload();
                            });
                        }
                    });
                }
            });
        },
        // 提交测量数据
        commit: function () {
            var itemList = getAllData('#jqGrid');
            var message = '提交后无法继续修改测量值，是否继续？';
            for (let i = 0; i < itemList.length; i++) {
                if(!itemList[i].measuredValue){
                    message = '尚有测量值未填写，提交后无法继续修改测量值，是否继续？';
                    break;
                }
            }
            confirm(message, function () {
                Ajax.request({
                    url: '../toolscheckticketitem/commit?toolsCheckTicketId=' + vm.ticketId,
                    params: {},
                    type: 'POST',
                    successCallback: function (res) {
                        alert('提交成功!', function (index) {
                            window.parent.location.reload();
                            // 关闭当前页面
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                        });
                    }
                });
            });
        },
        query: function () {
            vm.reload();
        },
        // 加载工单关联的工装列表
        loadTicketToolsBaseList: function () {
            Ajax.request({
                url: "../toolscheckticket/" + vm.ticketId + "/toolsBase",
                async: true,
                successCallback: function (r) {
                    vm.toolsBaseList = r.toolsBaseList;
                }
            });
        },
        reload: function (event) {
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var queryParam = {};
            if (vm.q.toolsFileId) {
                queryParam.toolsFileId = vm.q.toolsFileId;
            }
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: queryParam,
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                toolsFileId: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    }
});
